<template>
  <div>
    <div class="header">
      <el-button type="primary" @click="showAddDialog">添加IP</el-button>
    </div>
    <el-table :data="ipList">
      <el-table-column prop="ip" label="IP地址" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="danger" @click="handleDelete(row.ip)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" title="添加IP">
      <el-form>
        <el-form-item label="IP地址">
          <el-input v-model="newIP" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAdd">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import api from '../api'
import { ElMessage, ElMessageBox } from 'element-plus'

const ipList = ref([]) // 存储IP列表
const dialogVisible = ref(false) // 控制弹窗显示
const newIP = ref('') // 存储新IP地址

// 从字符串中提取IP地址
const extractIP = (str) => {
  const ipPattern = /(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/g
  const matches = str.match(ipPattern)
  return matches ? matches[0] : null
}

// 加载数据
const loadData = async () => {
  try {
    const res = await api.getIPList()
    if (res.data.status === 1) {
      // 提取每条数据中的IP地址
      ipList.value = res.data.data.map((item) => ({
        ip: extractIP(item),
        raw: item // 保留原始数据
      }))
    }
  } catch (error) {
    console.error('加载数据失败:', error)
  }
}

// 显示添加IP弹窗
const showAddDialog = () => {
  dialogVisible.value = true
}

// 验证IP地址格式
const validateIP = (ip) => {
  const pattern = /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/
  return pattern.test(ip)
}

// 添加IP
const handleAdd = async () => {
  if (!validateIP(newIP.value)) {
    ElMessage.error('IP地址格式不正确')
    return
  }

  try {
    await ElMessageBox.confirm('确认添加该IP吗？', '提示')
    const res = await api.addIP(newIP.value)
    if (res.data.status === 1) {
      ElMessage.success('添加成功')
      loadData() // 重新加载数据
      dialogVisible.value = false
      newIP.value = ''
    }
  } catch (error) {
    // 用户取消
  }
}

// 删除IP
const handleDelete = async (ip) => {
  try {
    await ElMessageBox.confirm('确认删除该IP吗？', '提示')
    const res = await api.deleteIP(ip)
    if (res.data.status === 1) {
      ElMessage.success('删除成功')
      loadData() // 重新加载数据
    }
  } catch (error) {
    // 用户取消
  }
}

// 组件挂载时加载数据
onMounted(loadData)
</script>

<style scoped>
.header {
  margin-bottom: 20px;
}
</style>